package com.monkeyboy.security.service;

import com.monkeyboy.common.exception.GlobalException;
import com.monkeyboy.dao.BaseDao;
import com.monkeyboy.model.SysUser;
import com.monkeyboy.security.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 用户验证处理
 *
 * @author
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private BaseDao bd;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Map<String, Object> userInfo = null;
        try {
            userInfo = (Map<String, Object>) bd.findForObject("UserMapper.selectUserByUsername", username);
            if (userInfo == null) {
                throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }

        SysUser user = new SysUser();
        user.setPassword(String.valueOf(userInfo.get("password")));
        user.setUserId(Integer.valueOf(String.valueOf(userInfo.get("user_id"))));
        user.setPhonenumber(String.valueOf(userInfo.get("phonenumber")));
        user.setStatus(String.valueOf(userInfo.get("status")));
        user.setUserName(String.valueOf(userInfo.get("username")));
        if ("0".equals(user.getStatus())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new GlobalException("对不起，您的账号：" + username + " 已被删除");
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
        //根据用户id查询用户的权限,角色信息，这儿只查询权限信息
        Set<String> perms = new HashSet<>();
        //这儿设置一个固定的role信息，后期自己从数据库里面获取角色信息
        Set<String> roles = new HashSet<>();
        roles.add("admin");
        if (user.isAdmin()) {
            perms.add("*:*:*");
        } else {
            try {
                List<String> userPerms = (List<String>) bd.findForList("UserMapper.selectMenuPermsByUserId", user.getUserId() + "");
                if (userPerms != null && userPerms.size() > 0) {
                    for (String perm : userPerms) {
                        perms.add(perm);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new GlobalException("权限异常，请稍后重试。");
            }
        }
        return new LoginUser(user, perms, roles);
    }
}
